﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace DIPLib
{
    public class HistogramProcessing
    {
        public static int[] getHistogram(byte[] rgbData)
        {
            int len = rgbData.Length;
            int[] mHistogramData = new int[256];

            for (int i = 0; i < len; i += 4)
            {
                mHistogramData[rgbData[i]] += 1;
            }
            return mHistogramData;
        }

        public static void applyHistEqualization(byte[] rgbData, int imageWidth, int imageHeight)
        {
            int[] hisData = new int[256];
            hisData = getHistogram(rgbData);

            // Calculate sum of histogram.
            int[] sumOfHis = new int[256];
            int sum = 0;
            for (int i = 0; i < sumOfHis.Length; i++)
            {
                sum += hisData[i];
                sumOfHis[i] += sum;

            }

            long area = imageWidth * imageHeight;
            int len = rgbData.Length;
            for (int i = 0; i < len; i += 4)
            {
                byte greyLevel = rgbData[i];
                byte newGrayLevel = (byte)(255 * sumOfHis[greyLevel] / area);
                rgbData[i] = rgbData[i + 1] = rgbData[i + 2] = rgbData[i + 3] = newGrayLevel;
            }
        }
    }
}
